# coding=utf-8
import datetime
import hashlib
import random


class TimeTools:
    @staticmethod
    def getDifferText(date):
        now = datetime.datetime.now()
        days = (now - date).days
        seconds = (now - date).seconds
        year = days / 365
        days -= year * 365
        month = days / 30

        hour = seconds / 60 / 60
        seconds -= hour * 60 * 60
        min = seconds / 60
        seconds -= min * 60

        if year > 0:
            return '%s年' % year
        elif month > 0:
            return '%s个月' % month
        elif days > 0:
            return '%s天' % days
        elif hour > 0:
            return '%s小时' % hour
        elif min > 0:
            return '%s分钟' % min
        elif seconds >= 0:
            return '%s秒钟' % seconds


class WashTools:
    white_list = ['title', 'id', 'date', 'comments', 'tags', 'descripition', 'path']

    @staticmethod
    def washHeader2Field(dic, path, title=None):
        if title is None:
            title = path.split('/')[-1][:-3]
        if 'title' not in dic or dic['title'].strip() == '':
            dic['title'] = title

        if 'id' not in dic or dic['id'].strip() == '':
            dic['id'] = str(hashlib.md5(str(random.random())).hexdigest())
        if 'date' not in dic or dic['id'].strip() == '':
            dic['date'] = datetime.datetime.now()
        else:
            try:
                if '/' in dic['date']:
                    dic['date'] = datetime.datetime.strptime(dic['date'], '%Y/%m/%d %H:%M:%S')
                else:
                    dic['date'] = datetime.datetime.strptime(dic['date'], '%Y-%m-%d %H:%M:%S')
            except ValueError:
                dic['date'] = datetime.datetime.now()
        if 'comments' not in dic or dic['comments'].strip() == '':
            dic['comments'] = 'True'
        if 'path' not in dic or dic['path'].strip() == '':
            dic['path'] = path

        if 'descripition' not in dic:
            dic['descripition'] = ''
        if 'tags' not in dic:
            dic['tags'] = ''
        td = dic.copy()
        for k in td.iterkeys():
            if k not in WashTools.white_list:
                del dic[k]
        return dic
